<template>
    <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
                class="-mb-15px"
                :model="queryParams"
                ref="queryFormRef"
                :inline="true"
                label-width="68px"
        >
            <el-form-item label="任务ID" prop="taskId">
                <el-input
                        v-model="queryParams.taskId"
                        placeholder="请输入任务ID，关联到活动任务"
                        clearable
                        @keyup.enter="handleQuery"
                        class="!w-240px"
                />
            </el-form-item>
            <el-form-item label="失败号码" prop="number">
                <el-input v-model="queryParams.number" placeholder="请输入失败的电话号码" clearable @keyup.enter="handleQuery" class="!w-240px" />
            </el-form-item>
            <el-form-item label="索引位置" prop="indexs">
                <el-input v-model="queryParams.indexs" placeholder="请输入在客户数组中的索引位置" clearable @keyup.enter="handleQuery" class="!w-240px" />
            </el-form-item>
            <el-form-item label="MD5值" prop="numberMd5">
                <el-input v-model="queryParams.numberMd5" placeholder="请输入电话号码的MD5值" clearable @keyup.enter="handleQuery" class="!w-240px" />
            </el-form-item>
            <el-form-item label="号码标签" prop="tag">
                <el-input v-model="queryParams.tag" placeholder="请输入号码标签" clearable @keyup.enter="handleQuery" class="!w-240px" />
            </el-form-item>
            <el-form-item label="错误信息" prop="errorMessage">
                <el-input v-model="queryParams.errorMessage" placeholder="请输入错误信息" clearable @keyup.enter="handleQuery" class="!w-240px" />
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
                <el-date-picker
                        v-model="queryParams.createTime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        type="daterange"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                        class="!w-220px"
                />
            </el-form-item>
            <el-form-item>
                <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
                <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
                <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['vos:activity-failed-numbers:create']">
                    <Icon icon="ep:plus" class="mr-5px" /> 新增
                </el-button>
                <el-button type="success" plain @click="handleExport" :loading="exportLoading" v-hasPermi="['vos:activity-failed-numbers:export']">
                    <Icon icon="ep:download" class="mr-5px" /> 导出
                </el-button>
                <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch" v-hasPermi="['vos:activity-failed-numbers:delete']">
                    <Icon icon="ep:delete" class="mr-5px" /> 批量删除
                </el-button>
            </el-form-item>
        </el-form>
    </ContentWrap>

  <!-- 列表 -->
    <ContentWrap>
        <el-table
                row-key="id"
                v-loading="loading"
                :data="list"
                :stripe="true"
                :show-overflow-tooltip="true"
                @selection-change="handleRowCheckboxChange"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column label="自增ID" align="center" prop="id" />
            <el-table-column label="任务ID" align="center" prop="taskId" />
            <el-table-column label="失败号码" align="center" prop="number" />
            <el-table-column label="索引位置" align="center" prop="indexs" />
            <el-table-column label="号码MD5值" align="center" prop="numberMd5" />
            <el-table-column label="号码标签" align="center" prop="tag" />
            <el-table-column label="错误信息" align="center" prop="errorMessage" />
            <el-table-column
                    label="记录的创建时间"
                    align="center"
                    prop="createTime"
                    :formatter="dateFormatter"
                    width="180px"
            />
            <el-table-column label="操作" align="center" min-width="120px">
                <template #default="scope">
                    <el-button link type="primary" @click="openForm('update', scope.row.id)" v-hasPermi="['vos:activity-failed-numbers:update']"> 编辑 </el-button>
                    <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['vos:activity-failed-numbers:delete']"> 删除 </el-button>
                </template>
            </el-table-column>
        </el-table>

        <Pagination
                :total="total"
                v-model:page="queryParams.pageNo"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />
    </ContentWrap>

    <ActivityFailedNumbersForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ActivityFailedNumbersApi, ActivityFailedNumbers } from '@/api/vos/activityfailednumbers'
import ActivityFailedNumbersForm from '../../activityfailednumbers/ActivityFailedNumbersForm.vue'

defineOptions({ name: 'ActivityFailedNumbers' })

const message = useMessage()
const { t } = useI18n()
const { query } = useRoute() // ★ 新增：读取路由上的 taskId

const loading = ref(true)
const list = ref<ActivityFailedNumbers[]>([])
const total = ref(0)
const queryParams = reactive({
    pageNo: 1,
    pageSize: 10,
    taskId: undefined as number | undefined, // ★ 新增到默认查询项
    number: undefined as string | undefined,
    indexs: undefined as number | undefined,
    numberMd5: undefined as string | undefined,
    tag: undefined as string | undefined,
    errorMessage: undefined as string | undefined,
    createTime: [] as string[] | []
})
const queryFormRef = ref()
const exportLoading = ref(false)

/** 查询列表 */
const getList = async () => {
    loading.value = true
    try {
        // 普通分页（支持附带 taskId 等筛选条件）
        const data = await ActivityFailedNumbersApi.getActivityFailedNumbersPage(queryParams)
        list.value = data.list
        total.value = data.total
    } finally {
        loading.value = false
    }
}

const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
}

const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
    formRef.value.open(type, id)
}

const handleDelete = async (id: number) => {
    try {
        await message.delConfirm()
        await ActivityFailedNumbersApi.deleteActivityFailedNumbers(id)
        message.success(t('common.delSuccess'))
        await getList()
    } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: ActivityFailedNumbers[]) => {
    checkedIds.value = records.map((item) => item.id)
}

const handleDeleteBatch = async () => {
    try {
        await message.delConfirm()
        await ActivityFailedNumbersApi.deleteActivityFailedNumbersList(checkedIds.value)
        checkedIds.value = []
        message.success(t('common.delSuccess'))
        await getList()
    } catch {}
}

const handleExport = async () => {
    try {
        await message.exportConfirm()
        exportLoading.value = true
        const data = await ActivityFailedNumbersApi.exportActivityFailedNumbers(queryParams)
        download.excel(data, '活动任务失败的具体名单号码信息.xls')
    } catch {
    } finally {
        exportLoading.value = false
    }
}

/** 初始化 **/
onMounted(() => {
    // ★ 新增：若路由带有 taskId，则默认带入筛选
    if (query.taskId) {
        const n = Number(query.taskId as string)
        if (!Number.isNaN(n)) queryParams.taskId = n
    }
    getList()
})
</script>
